
import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/common_widget.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/im/util/time.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:find_friend/pages/mine/mine_xspace.dart';
import 'package:find_friend/pages/xspace/detail/xcomment.dart';
import 'package:find_friend/pages/xspace/model/artclemodel.dart';
import 'package:find_friend/pages/xspace/school/view/xall_cell_image.dart';
import 'package:find_friend/pages/xspace/school/view/xcommbar.dart';
import 'package:flutter/cupertino.dart';
import 'package:page_transition/page_transition.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../model/school_model.dart';
import 'package:flutter/material.dart';

import 'xdetail_cell.dart';
import 'xdiscussdetail.dart';

class XDetailPage extends StatefulWidget {

  final ArticleModel model;
  final Function onRefreshData;

  XDetailPage({Key key, this.model, this.onRefreshData}) : super(key: key);

  @override
  _XDetailPageState createState() => _XDetailPageState();
}

class _XDetailPageState extends State<XDetailPage> {
  
  FocusNode _focusNode = FocusNode();
  bool ishot = true; // 是否是最热
  List<ReplyModel> list = [];
  ArtcleReplyListModel detailModel = ArtcleReplyListModel();
  int page = 0;
  RefreshController _refreshController = RefreshController(initialRefresh: true);
  XCommentWidget _commentWidget;
  bool isshowButton = true; /// 是否显示关注按钮
  bool requestFail = false; /// 是否网络请求失败
  bool isfollow = false; /// 是否关注
  bool isrefreshList = false; /// 是否要刷新x区列表

  @override
  void initState() {
    super.initState();

    setState(() {
      _commentWidget = XCommentWidget(
        articleId: widget.model.id.toString(),
        focusNode: _focusNode,           // 焦点
        onRefreshData: (bool isrefresh){
          if(isrefresh) {
            _onCommentRefresh(isrefresh);
          } 
        }, // 刷新数据
      );
    });

  }


  _requestCommlist({isrefresh = false}) {
    Networktool.request(API.article + "/" + widget.model.id.toString(), params: {"rows": 10, "page": page, "upvote_order": ishot}, method: NETWORKHTTPMethod.GET, success: (data){
      if(data != null && data["data"] != null){
        if(data["data"] != null) {
          ArtcleReplyListModel model = ArtcleReplyListModel.fromJson(data["data"]);
          detailModel = model;
          widget.model.upvotes = model.upvotes;
          widget.model.replys = model.replys;
          if(isrefresh) list.clear();
          SharedUserInfo.instance().then((value) => isshowButton = value.mobile == model.mobile);
          _endNormoreData(model.reply?.length ?? 0);
          setState(() {
            requestFail = false;
            if(model.reply != null)list.addAll(model.reply);
          });
        }
      }
    }
    ,fail: (msg) {
       AlertTool.showToast(msg);
       setState(() {
         requestFail = true;
       });
    }
    ,finaly: _endrefres);
  }

  _clear() {
    if(_focusNode != null) _focusNode.unfocus();
  }

  _onCommentRefresh(bool isreload){
    _clear();
    if(isreload) _refreshController.requestRefresh();
  }

   _onRefresh() {
    page = 1;
    _requestCommlist(isrefresh: true);
  }

  _onLoading() {
    page += 1;
    _requestCommlist();
  }

  _endrefres() {
    if(_refreshController.isRefresh) _refreshController.refreshCompleted();
    if(_refreshController.isLoading) _refreshController.loadComplete();
  }

  _endNormoreData(int perpage) {
    if(perpage < 5) {
      _refreshController.loadNoData();
    } else {
      _refreshController.loadComplete();
    }
  }

  Widget _getDataWidget() {
    final size = MediaQuery.of(context).size;
    if(requestFail == true) {
      return NoNetWorkPlacholder(onTap: () => _onRefresh(),);
    } else {
      return CustomRefreshWidget(
        onLoading: _onLoading,
        onRefresh: _onRefresh,
        controller: _refreshController,
        page: page,
        child: ListView.builder(
          itemCount: list.length + 1,
          padding: const EdgeInsets.only(bottom: 50),
          itemBuilder: (context, index){
            // 帖子详情
            if(index == 0) {
              return Stack(
                children: [
                  Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(top: 10, left: 20.5),
                      child: Row(
                        children: [
                          InkWell(
                            onTap: (){
                              Navigator.of(context).pushNamed("/minepreview", arguments: detailModel?.mobile);
                            },
                            child: CustomCircleAvatar(url: detailModel?.avatar, size: 46.h,)
                          ),
                          SizedBox(width: 8,),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(detailModel?.remarkname ?? "", style: instanceTextStyle(13, APP_font_black),),
                                Padding(
                                  padding: const EdgeInsets.only(right: 50, top: 2),
                                  child: Text("个性签名：${detailModel?.bio ?? "这个人很懒什么都没有！"}", maxLines: 1, overflow: TextOverflow.ellipsis, style: instanceTextStyle(9, APP_font_grey),),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    
                    SizedBox(height: 9),
                    // 文本消息
                    Offstage(
                      offstage: detailModel.content == null,
                      child: Padding(
                        padding: const EdgeInsets.only(left:20.0, bottom: 9.5),
                        child: Text(detailModel.content ?? "", style: instanceTextStyle(12, APP_font_black),),
                      ),
                    ),

                    // 图片
                    Offstage(
                      offstage: detailModel.photo == null,
                      child: Container(
                        padding: const EdgeInsets.only(left: 20),
                        child: XallImageWidget(list: detailModel.photo ?? [],)
                      ),
                    ),

                    // 语音
                    Offstage(
                      offstage: detailModel.voice == null,
                      child: Padding(
                        padding: const EdgeInsets.only(left:20.0, top: 9),
                        child: XspaceVoiceView(width: size.width * 0.45, voice: detailModel?.voice,),
                      ),
                    ),
                    
                    Padding(
                      padding: const EdgeInsets.only(left: 20, top: 9),
                      child: Text(TimeUtil.convertTime(detailModel.createtime == null ? 0 : detailModel.createtime * 1000), style: instanceTextStyle(9, APP_font_grey)),
                    ),
                    // 评论
                    XpageCommentWidget(
                      model: widget.model,
                      onRefreshData: (){
                        isrefreshList = true;
                      },
                      onTapComment: (){
                        _focusNode.requestFocus();
                      },
                    ),

                    Container(
                      color: APP_scaffold_back_color,
                      padding: const EdgeInsets.only(top: 9,),
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 20.5, vertical: 10),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border(bottom: BorderSide(color: APP_divider_color, width: 0.5))
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("评论", style: instanceTextStyle(15, APP_font_black),),
                            GestureDetector(
                              onTap: (){
                                setState(() {
                                  ishot = !ishot;
                                });
                                _refreshController.requestRefresh();
                              },
                              child: Container(
                                width: 50,
                                height: 20,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: [
                                  Text(ishot ? "热":"新", style: instanceTextStyle(11, ishot ? APP_verify_error_color : const Color(0xff00CEE6))),
                                  SizedBox(width: 2.5,),
                                  Image.asset("assets/re.png", color: ishot ? APP_verify_error_color : const Color(0xff00CEE6),)
                                ]),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),

                    /// 没有评论数据
                    Offstage(
                      offstage: list.length != 0,
                      child: Container(
                        width: size.width,
                        padding: const EdgeInsets.symmetric(vertical: 15),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Image.asset("assets/que2.png"),
                            SizedBox(height: 5,),
                            Text("别走~此处需要你的评论", style: TextStyle(fontFamily: "cute", fontSize: 15, color: Colors.black),),
                          ],
                        ),
                      ),
                    )
                  ]),

                  // 关注按钮
                  Positioned(
                    right: 15.5,
                    top: 15.5,
                    child: Offstage(
                      offstage: isshowButton,
                      child: XDetailFollowButton(model: detailModel, isfollow: detailModel.followflag != null,)
                    )
                  )
                ],
              );
            } else {
              // 评论
              return InkWell(
                onTap: (){
                    showBottomSheet(context: context, backgroundColor: Colors.black, elevation: 10, builder: (context){
                      return XDiscussDetailPage(aid: detailModel.id.toString(),model: list[index - 1],onRefreshDetail: _onRefresh,);
                    });
                  },
                  onLongPress: (){
                    AlertTool.showBottomShareDialog(context, replyModel: list[index - 1], onRefreshData: (){
                      setState(() {
                        list.removeAt(index - 1);
                      });
                    });
                  },
                  child: XdetailDiscussCell(
                    model: list[index - 1],
                    onRefreshData: () {
                      _refreshController.requestRefresh();
                    },
                    onReply: (name, id) {
                      _commentWidget.requestFocus(replyname: name, rid: id);
                    },
                    onShouldReloadList: () => isrefreshList = true,
                  ),
              );
            }
          }
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      // appBar: AppBar(
      //   backgroundColor: Colors.white,
      //   centerTitle: true,
      //   title: Text("帖子详情"),
      //   leading: IconButton(
      //     onPressed: (){
      //       if(widget.onRefreshData != null && isrefreshList) widget.onRefreshData();
      //       Navigator.of(context).pop();
      //     },
      //     icon: Image.asset("assets/fanhui.png"),
      //   ),
      //   actions: [
      //     IconButton(
      //       onPressed: (){
      //         AlertTool.showBottomShareDialog(context, articleModel: widget.model, onRefreshData: (){
      //           if(widget.onRefreshData != null) widget.onRefreshData();
      //           Navigator.pop(context);
      //         });
      //       },
      //       icon: Icon(Icons.more_horiz),
      //     )
      //   ],
      // ),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: (){
          _clear();
        },
        child: SafeArea(
          child: SizedBox(
            height: MediaQuery.of(context).size.height,
            child: Stack(
              children: [
                Positioned.fill(
                  child: Column(
                    children: [
                      AppBar(
                        backgroundColor: Colors.white,
                        centerTitle: true,
                        title: Text("帖子详情"),
                        leading: IconButton(
                          onPressed: (){
                            if(widget.onRefreshData != null && isrefreshList) widget.onRefreshData();
                            Navigator.of(context).pop();
                          },
                          icon: Image.asset("assets/fanhui.png"),
                        ),
                        actions: [
                          IconButton(
                            onPressed: (){
                              AlertTool.showBottomShareDialog(context, articleModel: widget.model, onRefreshData: (){
                                if(widget.onRefreshData != null) widget.onRefreshData();
                                Navigator.pop(context);
                              });
                            },
                            icon: Icon(Icons.more_horiz),
                          )
                        ],
                      ),
                      Expanded(child: _getDataWidget())
                    ],
                  ),
                ),
                Positioned(
                  bottom: 0,
                  child: _commentWidget,
                )
              ],
            ),
          ),
        ),
      )
    );
  }
}

class XDetailFollowButton extends StatefulWidget {
  
  final ArtcleReplyListModel model;
  bool isfollow;
  XDetailFollowButton({Key key, this.model, this.isfollow = false}) : super(key: key);

  @override
  _XDetailFollowButtonState createState() => _XDetailFollowButtonState();
}

class _XDetailFollowButtonState extends State<XDetailFollowButton> {

  // 关注
  _request() {
    Networktool.request(API.follow, params: {widget.isfollow ? "mobiles" : "mobile": widget.model.mobile}, method: widget.isfollow ? NETWORKHTTPMethod.DELETE : NETWORKHTTPMethod.POST, success: (data){
      setState(() {
        widget.isfollow = !widget.isfollow;
      });
    },
    fail: (msg) => AlertTool.showToast(msg));
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap:_request,
      child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
          decoration: BoxDecoration(
            color: widget.isfollow ? APP_main_color : Colors.white,
            borderRadius: BorderRadius.circular(20),
            border: Border.all(color:APP_main_color, width: 0.5)
          ),
          child: Text(widget.isfollow ? "已关注":"关注", style: instanceTextStyle(13, widget.isfollow ? Colors.white : APP_main_color),),
        ),
    );
  }
}

